package com.youth.framework.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.util.AntPathRequestMatcher;
import org.springframework.security.web.util.RequestMatcher;

import com.youth.framework.authority.entity.Resources;
import com.youth.platform.dao.SystemDao;

//1 加载资源与权限的对应关系
public class MySecurityMetadataSource implements
		FilterInvocationSecurityMetadataSource {

	@Resource(name = "systemDao")
	private SystemDao systemDao;
	
	private RequestMatcher pathMatcher;

	// 由spring调用
	public MySecurityMetadataSource(SystemDao systemDao) {
		this.systemDao = systemDao;
		loadResourceDefine();
	}

	// 返回所请求资源所需要的权限
	public Collection<ConfigAttribute> getAttributes(Object object)
			throws IllegalArgumentException {
		Iterator<String> it = resourceMap.keySet().iterator();
		while (it.hasNext()) {
			String resURL = it.next();
			Iterator<String> ite = resourceMap.keySet().iterator();
			pathMatcher = new AntPathRequestMatcher(resURL);
			if (pathMatcher.matches(((FilterInvocation) object).getRequest())) {
				Collection<ConfigAttribute> returnCollection = resourceMap
						.get(resURL);
				return returnCollection;
			}
		}
		return null;
	}

	public Collection<ConfigAttribute> getAllConfigAttributes() {
		return null;
	}

	public boolean supports(Class<?> clazz) {
		return true;
	}

	// 加载所有资源与权限的关系
	private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

	private void loadResourceDefine() {
		if (resourceMap == null) {
			resourceMap = new HashMap<String, Collection<ConfigAttribute>>();
			// 获取所有资源
			List<Resources> resources = this.systemDao.queryAllResources();
			for (Resources resource : resources) {
				Collection<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
				ConfigAttribute configAttribute = new SecurityConfig("ROLE_"
						+ resource.getResourceName());
				configAttributes.add(configAttribute);
				// 把对应的资源放入
				resourceMap.put(resource.getResourceString(), configAttributes);
			}
		}
	}

}
